# https://g1879.gitee.io/drissionpagedocs/WebPage/intro
import json
from operator import index
import random
from time import sleep
from DrissionPage import WebPage


from DrissionPage import ChromiumOptions

import os,re

os.environ["DISPLAY"] = "localhost:10.0"

LOGIN_USER_NAME = re.compile("无敌小宝")

# print(os.environ)
# 设置参数 https://g1879.gitee.io/drissionpagedocs/ChromiumPage/create_page_obj/
path = "/usr/bin/google-chrome-stable"

# https://g1879.gitee.io/drissionpagedocs/QandA
co = (
    ChromiumOptions(ini_path="./dp_configs.ini")
    .set_browser_path(path)
    # .set_argument("--no-sandbox --hide-crash-restore-bubble")
    .set_argument("--no-sandbox")
    .set_pref("credentials_enable_service", False)
)
# 默认d模式创建对象
page = WebPage(chromium_options=co)

# 模式
print(page.mode)


# 跟监听器配合，可在获取到需要的数据包时，主动停止加载。
# page.set.load_mode.none()  # 设置加载模式为none


page.get("https://club.magedu.com/")  # 访问网站


def login():
    button = page.ele("立即登录")

    page.stop_loading()  # 主动停止加载
    if button:
        # page.stop_loading()  # 主动停止加载
        button.click("js")
        # 多重重定向时
        page.wait.url_change("https://edu.magedu.com/auth")
        print("url change")
        # 等待元素出现
        page.wait.ele_loaded("tx:授权登录")

        # 手工登陆
        # 进入未答疑区
        # https://g1879.gitee.io/drissionpagedocs/get_elements/simplify
        button = page.ele("tx:授权登录")

        if button:
            button.click("js")


login()


# 待解决







def get_data(item):

    gold_number = item.s_ele(".gold__number")
    if gold_number:
        gold_number = gold_number.text

    # question-header__title
    title = item.ele(".question-header")
    if title:
        title = title.text

    # question-body
    question_body = item.s_ele(".question-body")
    if question_body:
        question_body = question_body.text

    # user-info__name
    user_info__name = item.s_ele(".user-info__name")
    if user_info__name:
        user_info__name = user_info__name.text

    # user-info__published
    user_info__published = item.s_ele(".user-info__published")
    if user_info__published:
        user_info__published = user_info__published.text

    # scan ivu-divider ivu-divider-vertical
    scan = item.ele(".question-bottom").child(index=-1).child(index=-1)
    if scan:
        scan = scan.text

    # question-tag
    question_tag = item.ele(".question-tag")
    if question_tag:
        question_tag = question_tag.text

    return {
        "gold_number": gold_number,
        "title": title,
        "question_body": question_body,
        "user_info__name": user_info__name,
        "user_info__published": user_info__published,
        "scan": scan,
        "question_tag": question_tag,
    }


def get_response(q):
    """
    curl -X POST -H "Content-Type: application/json" -d '{
    "model": "gpt-3.5-turbo",
    "stream": false,
    "messages": [
    {
        "role": "user",
        "content": "hello, are you GPT 4?"
    }
    ]
    }' http://localhost:1337/v1/chat/completions

    """

    page = WebPage("s")
    payload = {
        "model": "gpt-3.5-turbo",
        "stream": False,
        "messages": [{"role": "user", "content": q}],
    }
    page.post(
        "http://192.168.113.134:1337/v1/chat/completions",
        data=json.dumps(payload),
        headers={"Content-Type": "application/json"},
    )

    if page.json:
        result = ""
        for choice in page.json["choices"]:
            result += choice["message"]["content"]
        return result
    return None

from g4f.client import Client
from g4f.Provider import *

import retry

@retry.retry(tries=100,delay=3,max_delay=10)
def get_response_v2(q):

    client = Client()
    response = client.chat.completions.create(
        model="google-gemini-pro",
        messages=[{"role": "user", "content": q}],
        provider=FreeChatgpt,
        proxy="http://192.168.0.30:7890"
    )
    return response.choices[0].message.content

import re

regx = re.compile("岗位推荐")


def answer_item(data, item):
    # 答疑
    title_ele = item.ele("css:.question-header__title.ellipsis")
    title_ele.click("js")
    ids = page.tab_ids
    page.wait.url_change("https://club.magedu.com/answers")



    latest_tab = page.get_tab(ids[0])


    # 判断是否回答过
    for item in latest_tab.s_eles("css:.user-meta__name.ellipsis"):
        if LOGIN_USER_NAME.search(item.text):
            print("已回答过")
            page.close_tabs(tabs_or_ids=[ids[0]])
            return

    latest_tab.wait.ele_loaded("t:textarea")    
    latest_tab.wait.ele_loaded("tx:提交回答")    
    textarea = latest_tab.ele("t:textarea")
    button = latest_tab.ele("tx:提交回答")

    # 解答问题
    q = f'请解答问题， {data["title"]}, 详情: {data["question_body"]}'
    result = get_response_v2(q)


    if not result:
        print("没有答案",q)
        # 关闭当前
        page.close_tabs(tabs_or_ids=[ids[0]])

        return
    
    textarea.input(result, clear=False)

    if button:
        button.click("js")
    sleep(5)
    page.close_tabs(tabs_or_ids=[ids[0]])

 

def pub_q(q):
    button = page.ele("tx:我要提问")
    page.stop_loading()
    button.click("js")
 
    button = page.ele("tx:知道了，开始提问")
    button.click("js")

    title = page('tx:title')

    title.input(q,clear=False)

    select_tags = page.ele('.select-tags__input')
    select_tags.click('js')

    # tags 加载
    page.wait.ele_loaded('.select-tags__top')
    selectTags = page.ele('.select-tags__top')
    sre = selectTags.ele('.classification')('tx:sre')
    sre.click('js')
    sre = selectTags.ele('.tags')('tx:sre')
    sre.click('js')
    import random 

    page.wait.ele_loaded('tx:悬赏M币')
    pub_price = page.ele('tx:悬赏M币')
    pub_price.click('js')
    
    golds = [1]
    target_gold = random.choice(golds)

    ele = page.wait.ele_loaded(f'tag:li@@text():{target_gold}')
    ele.click('js')


    page('tag:button@@text():发布问题').click('js')

    ele = page('tag:button@@text():我知道了')
    if ele:
        ele.click('js')


    ele = page('tag:a@@text():问答')
    if ele:
        ele.click('js')

    page.wait.url_change('club.magedu.com')

with open('prompt.txt','r') as fb:
    for line in fb.readlines():
        line = line.strip()
        if not line:
            continue

        pub_q(line)
        sleep(random.randint(1,10))